let span_account=document.getElementById("span_account");
let ss_account=sessionStorage.getItem("account");
span_account.innerText=ss_account;
let books = [
	{id: 1, name: 'Java从入门到放弃', price: 80, tdate: '2020-07-01', count: 1, account: "hehe"},
	{id: 2, name: 'Vue从入门到放弃', price: 90, tdate: '2020-07-02', count: 1, account: "haha"},
	{id: 3, name: 'Mysql从入门到放弃', price: 100.01, tdate: '2020-07-03', count: 1, account: "hehe"},
	{id: 4, name: '啥都从入门到放弃', price: 70.00, tdate: '2020-07-04', count: 1, account: "haha"},
];
let data = localStorage.getItem("data");
if(data) {
	books = JSON.parse(data);
}else {
	localStorage.setItem("data", JSON.stringify(books));
}
let $tbody = $("table").find("tbody");
// let table = document.getElementsByTagName("table")[0];
// let tbody = table.getElementsByTagName("tbody")[0];


// let ipt_name = document.getElementById("ipt_name");
// let ipt_low = document.getElementById("ipt_low");
// let ipt_top = document.getElementById("ipt_top");

update();
getTotal();
//搜索和价格
function search() {
	let name = $("input[id='ipt_name']").val();//获取书名
	console.log(name);
	let low = $("input[id='ipt_low']").val();//获取书名
	let top = $("input[id='ipt_top']").val();//获取书名
	if(name.trim().length === 0 && low.trim().length === 0 && top.trim().length === 0 ) {
		alert("请输入查询条件")
		return;
	}
	$tbody.empty();
	// clear();
	update({name, low, top});
	getTotal({name, low, top});
}

// function clear() {
// 	do{
// 		tbody.removeChild(tbody.firstChild);
// 	}while(tbody.hasChildNodes());
// }
function update(args) {
	console.log(args);
	for(let index in books) {
		// console.log(index);
		let item = books[index];
		//嵌套地狱：来个if或switch来个18层级嵌套
		// console.log(item.account, ss_account);
		//账号与书本之间的关联处理
		if(item.account !== ss_account) {
			continue;
		}
		//搜索功能
		if(args) {
			console.log(typeof args.name);
			console.log(typeof item.name);
			if(args.name.trim().length !== 0 && item.name.indexOf(args.name) === -1) {
				continue;
			}
			if(args.low.trim().length !== 0 && item.price < args.low) {
				continue;
			}
			if(args.top.trim().length !== 0 && item.price > args.top) {
				continue;
			}
		}
		let tr=`
		<tr >
		<td>${item.id}</td>
		<td>
		    <a href='#' onclick='edit(${index})'> ${item.name}</td></a>
		<td>${item.price}</td>
		<td>${item.tdate}</td>
		<td><button type="button" onclick="jian(${index})">-</button>
		${item.count}
		<button type="button" onclick="jia(${index})">+</button>
		</td>
		<td>
			<button type="button" onclick='edit(${index})'>编辑</button>
			<button type="button" onclick="del(${index})">删除</button>
		    <input  type="checkbox" value="${index}" name="cb_select" />
		</td>
		</tr>
		  `;
		  $tbody.append(tr);
		// console.log(args);
		
		// console.log(typeof(item));
		// let tr = document.createElement("tr");
		// tbody.appendChild(tr);
		
		// for(let val in item) {
		// 	 console.log(val);
		// 	 console.log(item[val]);
		// 	if(val === "account") {
		// 		continue;
		// 	}
		// 	let text = item[val];
		// 	let isHtml = false;
		// 	if (val === "name") {
		// 		text = `
		// 			<a href='#' onclick='edit(${index})'>${text}</a>
		// 		`;
		// 		isHtml = true;
		// 	}else if(val === 'count') {
		// 		text = `
		// 			<button type="button" onclick="jian(${index})">-</button>
		// 			<span>${text}</span>
		// 			<button type="button" onclick="jia(${index})">+</button>
		// 		`;
		// 		isHtml = true;
		// 	}
		// 	appendTd(tr, text, isHtml);
		// }
		// let opt = `
		// 	<button onclick='edit(${index})'>编辑</button>
		// 	<button onclick="del(${index})">删除</button>
		// 	<input  type="checkbox" value="${index}" name="cb_select" />
		// `;
		// appendTd(tr, opt, true);
	}
}
// function appendTd(tr, value, isHtml) {
// 	let td = document.createElement("td"); 
// 	if(isHtml) {
// 		td.innerHTML = value;
// 	}else {
// 		td.innerText = value;
// 	}
// 	tr.appendChild(td);
// }

function getTotal(args) {
	let total = 0;
	
	for(let item of books) {
		if(item.account !== ss_account) {
			continue;
		}
		//搜索功能
		if(args) {
			if(args.name.trim().length !== 0 && item.name !== args.name) {
				continue;
			}
			if(args.low.trim().length !== 0 && item.price < args.low) {
				continue;
			}
			if(args.top.trim().length !== 0 && item.price > args.top) {
				continue;
			}
		}
		total += item.price * item.count;
	}
	
	document.getElementById("span_result").innerText = total;
}

function jia(index){
	let item =books[index];
	item.count++;
	console.log(item.count);
	
	// let node=tbody.childNodes[index+1];
	// let span= node.getElementsByTagName("span")[0];
	// span.innerText=item.count;
	localStorage.setItem("data", JSON.stringify(books));
	$tbody.empty();
	update();
	getTotal();
}
function jian(index){
				let item =books[index];
				if (item.count===1) {
					return;
				}
				item.count--;//怎么把该变的count放入
				// let node=tbody.childNodes[index+1];
				// let span= node.getElementsByTagName("span")[0];
				// span.innerText=item.count;
				localStorage.setItem("data", JSON.stringify(books));
				$tbody.empty();
				update();
				getTotal();
			}

function add() {
	location.href = "add.html";
	sessionStorage.setItem("item", null);
}


function edit(index) {
	let item = books[index];
	sessionStorage.setItem("index", index);
	sessionStorage.setItem("item", JSON.stringify(item));
	location.href = "add.html";
}

function del(index) {
	let result = confirm("确认是否删除" + books[index].name + "这本书？");
	console.log(result);
	if(!result) {
		return;
	}
	//删除数组中的数据
	books.splice(index, 1);
	
	//clear();
	//更新localStorage
	localStorage.setItem("data", JSON.stringify(books));
	$tbody.empty();
	update();
	//更新价格
	getTotal();
}
//批量删除
$(function() {
				//id选择器、class、标签
				//属性选择器
				//筛选器，也叫过滤器。类似于CSS伪元素
				
				$("button[name='shangc']").click(function() {
					//获取选中的checkbox
					$("input[name='cb_select']:checked").each(function(index, item) {
						console.log(index,item);
						console.log(this);
						console.log($(this).val());
						
						$(this).parent().parent().empty();
						
						books.splice(-((parseInt($(this).val()))+1), 1);
					});
					$tbody.empty();
					//clear();
					//更新localStorage
					localStorage.setItem("data", JSON.stringify(books));
					update();
					//更新价格
					getTotal();
					
				});
			});
	//全选操作
	$("input[name='cb_select_all']").change(function() {
		//checkbox点击切换的两种状态区分
		// console.log(this.checked);//dom属性
		// console.log($(this).prop("checked"));//jq属性，可以赋值也可获取值
		// console.log($(this).attr("checked"));//jq属性 赋值操作比较多
		let _self = $(this);
		$("input[name='cb_select']").each(function(index, item) {
			// console.log(item);//item是dom元素
			// item.prop("checked", "true");
			// item.checked = true;//dom元素
			//标准版本，能实现功能
			// if(_self.prop("checked")) {
			// 	//将所有name为cb_select的checkbox设置为选中
			// 	$(item).prop("checked", true);//jq实现
			// }else {
			// 	//将所有name为cb_select的checkbox设置为不选中
			// 	$(item).prop("checked", false);//不需要将值使用""包裹，因为要使用boolean值
			// }
			//简化版本
			$(item).prop("checked", _self.prop("checked"));
		});
	});
	
	//下载表格
$(function(){
	$("button[name='down']").click(function() {
		saveJSON(data, 'jsonData.json');
	});
	function saveJSON(data, filename) {
	    if (!data) {
	        alert('data is null');
	        return;
	    }
	    if (!filename) filename = 'json.json'
	    if (typeof data === 'object') {
	        data = JSON.stringify(data);
	    }
		//转换为二进制数据
	    var blob = new Blob([data]);
	    var a = document.createElement('a');
	    a.download = filename;
	    a.href = window.URL.createObjectURL(blob);
		a.click();
	}
})